<template>
  <div class="meal-statistics">
    <el-row :gutter="24">
      <el-col
        :xs="24"
        :sm="24"
        :md="24"
        :lg="8"
        :xl="7"
      >
        <div class="left">
          <div class="card">
            <div class="cut-off-time">
              <div class="cut-off-time__key">报餐截止时间：</div>
              <el-time-picker
                v-model="cutOffTime.time"
                placeholder="请选择截止时间"
                :picker-options="{
                  selectableRange: '8:00:00 - 17:00:00'
                }"
                @change="setMealSubscriptCutOffTime"
              />

              <el-select
                v-model="cutOffTime.type"
                placeholder="请选择"
                style="margin-left: 20px;"
              >
                <el-option
                  label="中餐"
                  value="lunch"
                />
                <el-option
                  label="晚餐"
                  value="dinner"
                />
              </el-select>
            </div>

          </div>

          <div class="card today">
            <div class="card__header">
              <div class="title">{{ chartTitle[currentChart] }}</div>

              <el-date-picker
                v-model="params.time"
                type="date"
                placeholder="选择日期"
                size="mini"
                style="width: 110px;"
                :clearable="false"
                :picker-options="pickerOptionsStart"
                @change="dateTimeChange"
              />
            </div>

            <div style="margin-top: 20px;">
              <ChartCarousel
                :data="data"
                :loading="chartLoading"
                @change="handleChartChange"
              />
            </div>

          </div>

          <div class="card">
            <div class="card__header">
              <div class="title">本周用餐人数统计</div>
              <!--              <el-date-picker-->
              <!--                v-model="timeArr"-->
              <!--                type="daterange"-->
              <!--                start-placeholder="开始日期"-->
              <!--                end-placeholder="结束日期"-->
              <!--                :default-time="['00:00:00', '23:59:59']"-->
              <!--                disabled-->
              <!--                style="width: 240px;"-->
              <!--                size="mini"-->
              <!--              />-->
            </div>

            <template v-if="!barChartLoading">
              <div class="chart">
                <BarChart
                  :data="barChartData"
                  :x-axis-data="barChartXAxisData"
                />
              </div>
            </template>

            <template v-else>
              <div
                v-loading="barChartLoading"
                style="height: 300px;"
              />
            </template>
          </div>
        </div>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="24"
        :lg="16"
        :xl="17"
      >
        <div class="right">
          <div class="card" style="padding: 30px 30px 0 30px;">
            <Search v-model="listParams" @search="handleSearch" />
          </div>

          <div class="card">
            <List
              :list="list"
              :loading="listLoading"
            />

            <div style="display: flex; justify-content: end;">
              <Pagination
                v-if="total"
                style="margin-top: 20px; padding: 0;"
                :total="total"
                :limit="listParams.paginate"
                :page="listParams.page"
                layout="total, prev, pager, next, jumper"
                @pagination="pagination"
              />
            </div>

          </div>
        </div>
      </el-col>

    </el-row>

  </div>
</template>

<script>
import {
  getMealStatistics,
  getMealDataOfWeek,
  getMealList,
  getMealSubscriptCutOffTime,
  setMealSubscriptCutOffTime
} from '@/api/repast'
import dayjs from 'dayjs'
import { generateRandomHexColor } from '@/utils'
import RingChart from '@/views/repast/components/RingChart.vue'
import BarChart from '@/views/repast/components/BarChart.vue'
import ChartCarousel from '@/views/repast/components/ChartCarousel.vue'
import Search from '@/views/repast/components/Search.vue'
import List from '@/views/repast/components/List.vue'
import Pagination from '@/components/Pagination/index.vue'
export default {
  name: '',
  components: {
    Pagination,
    RingChart,
    BarChart,
    Search,
    List,
    ChartCarousel
  },
  data() {
    return {
      params: {
        time: dayjs().format('YYYY-MM-DD')
      },
      listParams: {
        department_id: null,
        state: 'success',
        isEat: null,
        time: [],
        page: 1,
        paginate: 10
      },
      data: null,
      currentWeekMealData: null,
      timeArr: [],
      list: [],
      total: 0,
      chartLoading: false,
      barChartLoading: false,
      listLoading: false,
      cutOffTime: {
        time: null,
        type: 'lunch'
      },
      chartTitle: {
        today: '今日用餐数据',
        diningRate: '实际用餐情况',
        departmentMealData: '各部门数据统计'
      },
      currentChart: 'today',
      cutOffTimeList: []
    }
  },
  computed: {
    mealDataFormat() {
      return [
        {
          label: '已用餐',
          color: '#66C23A',
          value: this.data?.isEat,
          unit: '人'
        },
        {
          label: '未用餐',
          color: '#2F88FF',
          value: this.data?.notEat,
          unit: '人'
        },
        {
          label: '超时申请',
          color: '#FAAD15',
          value: this.data?.notApply,
          unit: '人'
        }
      ]
    },
    chartTitleOptions() {
      const total = this.data?.totalUserCount
      const percent = parseFloat((this.data?.count / total * 100).toFixed(2))
      return {
        title: this.data?.count,
        subTitle: `${this.data?.count}/${total} (${percent}%)`
      }
    },
    ringChartData() {
      return this.data?.department.map(item => {
        return {
          label: item.department_name,
          value: item.mealCount,
          id: item.department_id,
          color: generateRandomHexColor()
        }
      })
    },
    barChartData() {
      return this.currentWeekMealData?.map(item => item?.mealCount)
    },
    barChartXAxisData() {
      const label = this.currentWeekMealData?.map(item => dayjs(item.date).format('MM.DD')) ?? []
      return [
        ...label,
        '(时间)'
      ]
    },
    pickerOptionsStart() {
      return {
        disabledDate: (time) => {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  watch: {
    'cutOffTime.type': {
      handler(n) {
        const time = this.cutOffTimeList
          .filter(item => item.type === this.cutOffTime.type)[0]?.time
        this.cutOffTime.time = this.timeFormat(time)
      }
    }
  },
  created() {
    this.getWeekDate()
    this.init()
  },
  methods: {

    init() {
      Promise.allSettled([
        this.getMealStatistics(),
        this.getMealDataOfWeek(),
        this.getMealList(),
        this.getMealSubscriptCutOffTime()
      ])
    },

    async getMealStatistics() {
      this.chartLoading = true
      try {
        const res = await getMealStatistics(this.params)
        this.data = res.data
      } catch (error) {
        throw new Error('Failed to get statistics data')
      } finally {
        await this.sleep()
        this.chartLoading = false
      }
    },

    async getMealDataOfWeek() {
      this.barChartLoading = true
      try {
        const res = await getMealDataOfWeek()
        this.currentWeekMealData = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await this.sleep()
        this.barChartLoading = false
      }
    },

    async getMealList() {
      this.listLoading = true
      try {
        const res = await getMealList(this.paramsFormat())
        this.list = res.data.data
        this.total = res.data.total
      } catch (error) {
        console.log('error --------->', error)
        this.$message.error(error?.response?.data?.message || '用餐信息获取失败')
      } finally {
        await this.sleep()
        this.listLoading = false
      }
    },

    paramsFormat() {
      const time = this.listParams?.time?.length ? JSON.stringify(this.listParams.time) : null
      const len = this.listParams?.department_id?.length
      const department_id = len ? this.listParams?.department_id[len - 1] : null
      return {
        ...this.listParams,
        time,
        department_id
      }
    },

    dateTimeChange(e) {
      this.params.time = dayjs(e).format('YYYY-MM-DD')
      this.getMealStatistics()
    },

    sleep(t = 500) {
      return new Promise(resolve => setTimeout(resolve, t))
    },

    getWeekDate() {
      const weekday = dayjs().day()
      const we = weekday === 0 ? 0 - 1 : 0

      const beginDate = dayjs().add(we, 'week').startOf('week').add(1, 'day')
      const endDate = dayjs().add(we, 'week').endOf('week').add(1, 'day')

      this.timeArr = [
        beginDate,
        endDate
      ]
    },

    pagination(page) {
      this.listParams.page = page.page
      this.listParams.paginate = page.limit
      this.getMealList()
    },

    handleSearch() {
      this.listParams.page = 1
      this.getMealList()
    },

    async getMealSubscriptCutOffTime() {
      try {
        const res = await getMealSubscriptCutOffTime()
        console.log('res --------->', res)
        const data = res.data?.filter(item => item?.type_id === 1)
        this.cutOffTimeList = data ?? []
        console.log('data --------->', data)
        const time = data?.filter(item => item.type === this.cutOffTime.type)[0]?.time
        this.cutOffTime.time = this.timeFormat(time)
        // this.cutOffTime.type = res.data?.type
      } catch (error) {
        console.log('error --------->', error)
      }
    },

    timeFormat(time) {
      if (!time) return null
      const today = dayjs().format('YYYY-MM-DD')
      return dayjs(`${today} ${time}`).format('YYYY-MM-DD HH:mm:ss')
    },

    async setMealSubscriptCutOffTime() {
      try {
        const res = await setMealSubscriptCutOffTime({
          time: dayjs(this.cutOffTime.time).format('HH:mm:ss'),
          type_id: 1,
          type: this.cutOffTime.type
        })
        this.$message.success('报餐截止时间设置成功')
        this.getMealSubscriptCutOffTime()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '报餐截止时间设置失败')
      }
    },

    handleChartChange(e) {
      this.currentChart = e
    }

  }
}
</script>

<style lang="scss" scoped>
* {
  font-family: Microsoft YaHei, Microsoft YaHei;
}
.meal-statistics {
  padding: 30px;
  //display: flex;

  .left {
    //width: 30%;
    margin-right: 3px;
    .cut-off-time {
      display: flex;
      align-items: center;

      &__key {
        color: #606266;
        font-size: 14px;
        min-width: 98px;
        text-align: right;
      }
    }

  }

  .right {
    margin-left: 3px;
    //margin-left: 30px;
    //width: 70%;
  }

}

::v-deep(.el-input__inner) {
  padding-right: 0;
}
</style>
